package com.example.proxy.handler;

import com.example.proxy.tx.CustomTransactionManager;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author yexi
 */
@Setter
@Getter
@Scope("prototype")
@Component
@ToString(callSuper = true)
public class TransactionInvocationHandler implements InvocationHandler {
    private Object target;
    private CustomTransactionManager tx;


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        Object retVal = null;
        try {
            tx.begin();
            retVal = method.invoke(target, args);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        }
        return retVal;
    }
}